package com.lbt.writing.config;

import com.lbt.writing.common.TokenException;
import com.lbt.writing.utils.JWTUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 放行 OPTIONS 请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }

        // 放行登录接口和文件上传下载接口
        String uri = request.getRequestURI();
        if (uri.contains("/user/login")
                || uri.contains("/common/upload")
                || uri.contains("/common/download")
                || uri.contains("/user/add")) {
            return true;
        }

        // 从请求头中获取token
        String token = request.getHeader("Authorization");

        // 如果没有token
        if (StringUtils.isEmpty(token)) {
            throw new TokenException("无token，请重新登录");
        }

        // 验证token
        if (!JWTUtils.verify(token)) {
            throw new TokenException("token无效，请重新登录");
        }

        return true;
    }
}
